package com.atguigu.service;

import com.atguigu.entity.Users;
import com.atguigu.mapper.UsersMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author：请允悲
 * @Slogan：致敬大师
 * @Package：com.atguigu.service
 * @Project：springsecuritydemo
 * @name：MyUserDetailsService
 * @Date：2023/9/27 12:14
 * @Filename：MyUserDetailsService
 */
@Service("userDetailsService")      //@Autowired private UserDetailsService userDetailsService;
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用users'Mapper方法根据用户名查询数据库
         QueryWrapper<Users> wrapper = new QueryWrapper();
         //where username=?
        wrapper.eq("username",username);
        Users users = usersMapper.selectOne(wrapper);

        if (users==null){//数据库没有用户名认证失败
            throw new UsernameNotFoundException("用户名不存在");
        }

        //
        List<GrantedAuthority> auths= AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_sale");
        //从查询数据库返回users对象，得到用户名和密码，返回
        return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);
    }
}
